package cn.edu.pku.sei.ra.framework;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;


public class ResourceEnv {
	
	protected ResourceSet resourceSet=null;
	
	protected ArrayList<String> globalRegistryKey;
	protected ArrayList<Object> globalRegistryPackage;
	
	public ResourceEnv(){
		globalRegistryKey=new ArrayList<String>();
		globalRegistryPackage=new ArrayList<Object>();
		for(Map.Entry<String,Object> entry:EPackage.Registry.INSTANCE.entrySet()){
			globalRegistryKey.add(entry.getKey());
			globalRegistryPackage.add(entry.getValue());
		}

//		EPackage.Registry.INSTANCE.clear();
		
		Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("xmi",
				new XMIResourceFactoryImpl());
		resourceSet = new ResourceSetImpl();
		resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put
		(
				Resource.Factory.Registry.DEFAULT_EXTENSION, 
				new XMIResourceFactoryImpl()
		);
		resourceSet.getPackageRegistry().put
		(EcorePackage.eNS_URI, 
				EcorePackage.eINSTANCE);
	}
	
	public EPackage getEPackage(URI uri){
		Resource rs=resourceSet.getResource(uri,true);
		for(Iterator it=rs.getContents().iterator();it.hasNext();)
		{
			Object ob=it.next();
			if(ob instanceof EPackage){
				return (EPackage)ob;
			}
		}
		return null;		
	}
	
	public void registerPackage(String modelURI,EPackage pack){
		//resourceSet
		EPackage.Registry.INSTANCE.remove(modelURI);
		resourceSet.getPackageRegistry().put(
				modelURI, 
				pack
			);
		EPackage.Registry.INSTANCE.put(
				modelURI, 
				pack
			);
	}
	
	public ResourceSet getResourceSet(){
		return resourceSet;
	}
	
	public Resource createInterResource(){
		String whatever="whatever"+String.valueOf(System.currentTimeMillis()%100000);
		return resourceSet.createResource(URI.createFileURI(whatever));
	}
	
	public void revertGloble(){
		EPackage.Registry.INSTANCE.clear();
		for(int i=0;i<globalRegistryPackage.size();i++){
			EPackage.Registry.INSTANCE.put(
					globalRegistryKey.get(i), 
					globalRegistryPackage.get(i)
			);
		}
	}
}
